package com.cskaoyan;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 创建日期: 2021/11/25 10:53
 *
 * @author ciggar
 * DBCP数据库连接池的工具类
 */
public class DBCPUtils {

    static DataSource dataSource;

    static {
        try {
            Properties properties = new Properties();


            // 在maven项目中，读取文件流，建议采用类加载器类读取
            ClassLoader classLoader = DBCPUtils.class.getClassLoader();

            URL url = classLoader.getResource("dbcp.properties");
            String path = url.getPath();

            FileInputStream fileInputStream = new FileInputStream(path);


            InputStream stream = classLoader.getResourceAsStream("dbcp.properties");

            properties.load(stream);



            dataSource = BasicDataSourceFactory.createDataSource(properties);


        }catch (Exception ex) {
            System.out.println("DBCP数据库连接池初始化异常...");
            ex.printStackTrace();
        }
    }

    // 获取连接的方法
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;

    }
}
